import React from "react";
import CountDown from "@/components/countdown"; // 引入封装好的组件
import type business from "@/types/business"; // 引入类型声明文件

type EmsValue = {
  email: string;
  code: string;
}

const Emails = () => {
  // 挂载表格组件
  const [form] = React.UI.Form.useForm();
  // 获取全局挂载的用户信息
  const [business] = useState<business>(React.business);

  // 检查是否添加了邮箱信息
  useEffect(() => {
    if (!business.email) {
      React.fail('请先绑定邮箱', () => {
        React.navigate('/business');
      })
    }
  }, [business.email])

  // 检查是否已经验证
  useEffect(() => {
    if (business.auth == '1') {
      React.fail('您已验证,无须重复验证', () => {
        React.navigate('/business');
      })
    }
  }, [business.auth])

  // 表单提交事件
  const onSubmit = async (values: EmsValue) => {
    // 组装参数
    const params = {
      ...values,
      busid: business.id
    };
    // 发起请求
    const result = await React.Http.post('/business/EmsCheck', params);
    // 处理请求结果
    if (result.code === 1) {
      React.success(result.msg, () => {
        // 返回上一页
        React.navigate(-1);
      });
    } else {
      React.fail(result.msg);
      // 清空表单
      form.setFieldValue('code', '');
    }
  };

  // 点击发送验证码按钮
  const SendEmail = async () => {
    // 组装参数
    const params = {
      busid: business.id,
      email: business.email
    };
    // 发起请求
    const result = await React.Http.post('/business/send', params);
    // 返回提示信息
    if (result.code === 1) {
      React.success(result.msg);
    } else {
      React.fail(result.msg);
    }
  }

  return (
    <>
      <React.UI.Form
        form={form}
        onFinish={onSubmit}
        layout="horizontal"
        footer={
          <React.UI.Button block type="submit" color="primary" size="large">
            提交
          </React.UI.Button>
        }
      >
        <React.UI.Form.Item
          initialValue={business.email ?? ''}
          rules={[
            { required: true, message: "请填写正确的邮箱" },
            { type: "email", warningOnly: true },
          ]}
          name="email"
          label="邮箱"
        >
          <React.UI.Input placeholder="请输入邮箱" />
        </React.UI.Form.Item>

        <React.UI.Form.Item
          label="邮箱验证码"
          // 自定义组件
          extra={
            <CountDown
              initialSeconds={60}
              buttonTextBefore="发送验证码"
              SendEmail={SendEmail}
            />
          }
          name="code"
          rules={[{ required: true, message: "验证码不能为空" }]}
        >
          <React.UI.Input placeholder="请输入邮箱验证码" />
        </React.UI.Form.Item>
      </React.UI.Form>
    </>
  );
};

export default Emails;